import React, { useState, useEffect } from 'react';
import { View, StyleSheet, ScrollView, Text, Dimensions } from 'react-native';
import { LineChart } from 'react-native-chart-kit';
import { useTheme } from '../theme/ThemeContext';
import { getDailyStats } from '../database/database';
import { formatDuration } from '../utils/timeUtils';
import { getDateRange } from '../utils/timeUtils';

export const StatisticsScreen = () => {
  const { theme } = useTheme();
  const [dailyStats, setDailyStats] = useState<{ date: string; totalDuration: number }[]>([]);
  const [totalDuration, setTotalDuration] = useState(0);
  const [averageDuration, setAverageDuration] = useState(0);

  useEffect(() => {
    loadStats();
  }, []);

  const loadStats = async () => {
    try {
      const { startDate, endDate } = getDateRange(7); // 获取最近7天的数据
      const stats = await getDailyStats(startDate, endDate);
      
      setDailyStats(stats);
      
      const total = stats.reduce((sum, stat) => sum + stat.totalDuration, 0);
      setTotalDuration(total);
      setAverageDuration(total / stats.length);
    } catch (error) {
      console.error('Error loading statistics:', error);
    }
  };

  const chartData = {
    labels: dailyStats.map(stat => {
      const date = new Date(stat.date);
      return `${date.getMonth() + 1}/${date.getDate()}`;
    }),
    datasets: [
      {
        data: dailyStats.map(stat => stat.totalDuration / 3600), // 转换为小时
      },
    ],
  };

  return (
    <ScrollView style={[styles.container, { backgroundColor: theme.colors.background }]}>
      <View style={styles.summaryContainer}>
        <View style={[styles.summaryCard, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.summaryLabel, { color: theme.colors.text }]}>
            总计时长
          </Text>
          <Text style={[styles.summaryValue, { color: theme.colors.primary }]}>
            {formatDuration(totalDuration)}
          </Text>
        </View>
        <View style={[styles.summaryCard, { backgroundColor: theme.colors.card }]}>
          <Text style={[styles.summaryLabel, { color: theme.colors.text }]}>
            日均时长
          </Text>
          <Text style={[styles.summaryValue, { color: theme.colors.secondary }]}>
            {formatDuration(averageDuration)}
          </Text>
        </View>
      </View>

      <View style={styles.chartContainer}>
        <Text style={[styles.chartTitle, { color: theme.colors.text }]}>
          最近7天统计
        </Text>
        <LineChart
          data={chartData}
          width={Dimensions.get('window').width - 32}
          height={220}
          chartConfig={{
            backgroundColor: theme.colors.card,
            backgroundGradientFrom: theme.colors.card,
            backgroundGradientTo: theme.colors.card,
            decimalPlaces: 1,
            color: (opacity = 1) => theme.colors.primary,
            labelColor: (opacity = 1) => theme.colors.text,
            style: {
              borderRadius: 16,
            },
            propsForDots: {
              r: '6',
              strokeWidth: '2',
              stroke: theme.colors.primary,
            },
          }}
          bezier
          style={{
            marginVertical: 8,
            borderRadius: 16,
          }}
          yAxisLabel=""
          yAxisSuffix="h"
        />
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  summaryContainer: {
    flexDirection: 'row',
    padding: 16,
    justifyContent: 'space-between',
  },
  summaryCard: {
    flex: 1,
    padding: 16,
    borderRadius: 12,
    marginHorizontal: 8,
    alignItems: 'center',
  },
  summaryLabel: {
    fontSize: 14,
    marginBottom: 8,
  },
  summaryValue: {
    fontSize: 18,
    fontWeight: 'bold',
  },
  chartContainer: {
    padding: 16,
  },
  chartTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 16,
  },
}); 